A callback function is a function that is passed as an argument to another function and is executed after the completion of that function. This is a common technique in JavaScript to handle asynchronous operations or customize behavior.
The function receiving the callback is responsible for invoking it at the appropriate time. Callbacks are widely used in JavaScript, especially in event handling, asynchronous operations, and array methods.
The following example demonstrates a callback function being passed to another function:
function processUserInput(callback) {
const name = prompt("Please enter your name:");
callback(name);
}
function greetUser(userName) {
console.log("Hello, " + userName + "!");
}
// Passing the greetUser function as a callback
processUserInput(greetUser);
Output: Displays a greeting with the entered name.
Callback functions are essential in JavaScript for managing asynchronous operations and extending the functionality of higher-order functions. They provide flexibility and allow developers to write clean, modular, and reusable code.